#!/usr/bin/env python

####

# @project: UbunTube
# @version = 0.1a
# @site UbunTube http://www.ubuntube.tk
# @copyright (c) 2009 Mohamed Nashmi
# @license http://opensource.org/licenses/gpl-license.php GNU Public License

####

import sys
try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gtk.glade
    import gobject
except:
    sys.exit(1)


from GUI import bars
from Videos import Library



class Main():
    """This is the base class that gets called when the program is started. It acts as the controller
        for the entire program. Each main widget:
            Top Bar
            Side Bar
            Notebook
            Library (Videos List)
        can be accessed from this class
    """

    def __init__(self):
        """Creates the main program and the GUI."""
        self.gladefile = "gui.glade"
        self.wTree = gtk.glade.XML(self.gladefile)
        #Get the Main Window, and connect the "destroy" event
        #:The main window of the application
        self.window = self.wTree.get_widget("window")
        if (self.window):
            self.window.connect("delete-event", self.safeClose)
            self.window.connect("expose-event", self.addLocalLibrary)
            self.window.connect("key-press-event", self.checkFullScreen)
        else:
            sys.exit(1)
            
        self.fullScreened = 0
        #: UbunTube notebook widget that holds the Library and any playing video
        self.notebook = Library.Library(self)
        #: UbunTube library is the gtk.IconView that holds the Library List
        self.library = Library.List(self)
        self.loadedLibrary = False
        
        #: UbunTube top bar which handles user Interaction and requests
        self.topBar = bars.Top(self)
        #:UbunTube side bar which *will* implement favorite videos and most played
        self.sideBar = bars.Side(self)
        self.sideBar.connect("showLibrary", self.library.showLibrary)
        self.sideBar.connect("showFavorites", self.library.showFavorites)
        
        logoPb = gtk.gdk.pixbuf_new_from_file(".thumbnails/icon.png")
        #UbunTube gtk.StatusIcon which allows the program to be minimized to ray
        self.trayIcon = gtk.status_icon_new_from_pixbuf(logoPb)
        self.trayIcon.set_visible( True )
        self.trayIcon.set_tooltip(("UbunTube"))
        self.trayIcon.connect("activate", self.trayApp)
        
        

        self.window.set_icon(logoPb)
        
        minimizetoTrayMenu = self.wTree.get_widget("menu_minimize_to_tray")
        minimizetoTrayMenu.connect("activate", self.trayApp)
        
        videoMenu = self.wTree.get_widget("menu_video")
        videoMenu.set_sensitive(False)
        

        
        
    def addLocalLibrary(self, window, event):
        """Imports the videos located in the local library to UbunTube Library.
        Once the video library is loaded, it makes sure the library isnt loaded again
        by setting the loadedLibrary variable
        """
        if not self.loadedLibrary:
            self.library.loadLocalFiles()
            self.loadedLibrary = True
        
        
    def trayApp(self, trayIcon):
        """Implements a minimize to tray feature for UbunTube by hiding or showing the 
        main window depending on the windows 'visible' property
        """
        if self.window.get_property('visible'):
            self.window.hide()
        else:
            self.window.show()
            
            
    def checkFullScreen(self, window, event):
        """Handles key press events in the window. Specifically the Escape key or the F key
        to allow the application to go into full screen"""
        key = gtk.gdk.keyval_name(event.keyval)
        if key == "Escape" or key == "f":
            self.fullScreenMode()
        
    def fullScreenMode(self):
        """Checks whether the application is in fullscreen mode or not and acts accordingly.
        Its called back when Escape or F key are pressed."""
        if self.fullScreened:
            self.sideBar.show()
            self.topBar.show()
            self.window.unfullscreen()
            self.notebook.noteBook.set_show_tabs(True)
            self.fullScreened = 0
        else:
            self.sideBar.hide()
            self.topBar.hide()
            self.window.fullscreen()
            self.notebook.noteBook.set_show_tabs(False)
            videoToolbar = self.wTree.get_widget("videotoolbar")
            videoToolbar.hide()
            self.fullScreened = 1
        
        
    def safeClose(self, window, event):
        """Implements a safe and clean application shutdown. We close any open page to make sure
        Mplayer doesnt run in the background even after gtk quits."""
        pages = self.notebook.noteBook.get_n_pages() - 1
        """
        Adds the file to the files list so that it can be loaded when the application
        starts. Files are listed in the '.files' file.
        """
        libraryUpdate = []
        for videoID in self.library.videos:
            if self.library.videos[videoID].favorite:
                fav = "T"
            else:
                fav = "F"
            videoDetails =  self.library.videos[videoID].file + ',' + fav + '\n'
            libraryUpdate.append(videoDetails)
        
        open('.files', 'w').writelines(libraryUpdate)
        
        while pages > 0:
            self.notebook.closePage(gtk.Button(), pages)
            pages -= 1
        gtk.main_quit()
        
        
        
    def createAboutDialog(self):
        """Creates the About dialog and returns a gtk.VBox which contais the packed
        widgets for the dialog to be shown
        """
        #:String contating the entire credits to be stored in the textview
        #Very ugly
        credits = '''Ubuntube

UbunTube is a graphical video library which is capable of importing youtube files or local files into a single application. UbunTube is written using GTK+ with the use of glade and pygtk.

You may modify and redistribute the program under the terms of the GPL (version 2 or later).  A copy of the GPL is contained in the 'COPYING' file distributed with Pidgin.  Pidgin is copyrighted by its contributors.  See the 'COPYRIGHT' file for the complete list of contributors.  We provide no warranty for this program.\n 
\tURL: http:// \n 
\tFAQ: http:// \n 
\tHelp via e-mail: admin@ubuntube.tk\n 
\tCurrent Developers:\n
\t\t* Mohamed Nashmi'''

        box = gtk.VBox()
        pb = gtk.gdk.pixbuf_new_from_file(".thumbnails/logo.png").scale_simple(100,100,gtk.gdk.INTERP_BILINEAR)
        img = gtk.image_new_from_pixbuf(pb)
        box.pack_start(img, False, False)
        swin = gtk.ScrolledWindow()
        swin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        textview = gtk.TextView()
        textview.set_wrap_mode(gtk.WRAP_WORD)
        textview.set_justification(gtk.JUSTIFY_LEFT)
        textview.set_indent(1)
        textview.set_editable(False)
        textbuffer = textview.get_buffer()
        swin.add(textview)
        swin.set_size_request(200, 300)
        textbuffer.set_text(credits)
        iter = textbuffer.get_start_iter()
        textview.scroll_to_iter(iter, 0)
        box.pack_start(swin, True, True, 10)
        return box
        
if __name__ == "__main__":
    ubunTube = Main()
    gtk.main()
